import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
// 1、定义 全局变量 globalData
const globalData = {
  message: "",
};
const MessageSetter = () => {
  const setMessage = (msg) => {
    globalData.message = msg; //先给全局变量赋值
    // 3、派发一个全局 globalDataChanged 事件
    window.dispatchEvent(new Event("globalDataChanged"));
  };
  return (
    <div>
      <button onClick={() => setMessage("hello from setter")}>
        Set Message
      </button>
    </div>
  );
};
const MessageViewer = () => {
  const [message, setMessage] = useState(globalData.message);
  React.useEffect(() => {
    const globalDataChangedHandler = () => setMessage(globalData.message);
    // 2、监听 globalDataChanged 事件，触发 globalDataChangedHandler
    window.addEventListener("globalDataChanged", globalDataChangedHandler);
    return () => {
      // 3、更新时，移除 globalDataChanged 事件
      window.removeEventListener("globalDataChanged", globalDataChangedHandler);
    };
  }, []);
  return <div>Message:{message}</div>;
};
// 不建议用
// 缺点一 ，需要两个组件在发送消息的时候都已经初始化了
// 缺点二 ，要求先初始化MessageViewer。再触发globalDataChanged事件
function App() {
  return (
    <div>
      <MessageSetter />
      <MessageViewer />
    </div>
  );
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
